package com.yvan.http;

import com.yvan.Conv;
import com.yvan.platform.JsonWapper;
import okhttp3.*;
import org.slf4j.Logger;

import java.io.IOException;
import java.util.Map;

public class Curl {
    private final Logger logger;
    private final OkHttpClient client;
    private final Request.Builder builder;
    private boolean debug;

    public Curl(OkHttpClient client, Logger logger) {
        builder = new Request.Builder();
        this.client = client;
        this.logger = logger;
    }


    public Curl get(String url) {
        this.url(url);
        builder.get();
        return this;
    }

    public Curl get() {
        builder.get();
        return this;
    }

    public Curl url(String url) {
        builder.url(url);
        return this;
    }

    public Curl postJson(String json) {
        builder.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json));
        return this;
    }

    public Curl post(String url, Map<String, ?> forms) {
        builder.url(url);
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        if (forms != null) {
            for (Map.Entry<String, ?> entry : forms.entrySet()) {
                bodyBuilder.add(entry.getKey(), Conv.NS(entry.getValue()));
            }
        }
        builder.post(bodyBuilder.build());
        return this;
    }

    public Response execute() {
        try {
            return client.newCall(builder.build()).execute();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public JsonWapper executeJson() {
        return new JsonWapper(executeText());
    }

    public String executeText() {
        try {
            return execute().body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
